package cn.itcast.starter.es.config;

import cn.itcast.starter.es.util.ElasticClient;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author 虎哥
 */
@Configuration
@EnableConfigurationProperties(ElasticProperties.class)
public class ElasticConfig {

    private final ElasticProperties properties;

    public ElasticConfig(ElasticProperties properties) {
        this.properties = properties;
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        List<String> hosts = properties.getHosts();
        HttpHost[] httpHosts = new HttpHost[hosts.size()];
        for (int i = 0; i < hosts.size(); i++) {
            httpHosts[i] = HttpHost.create(hosts.get(i));
        }
        return new RestHighLevelClient(
                RestClient.builder(httpHosts)
        );
    }

    @Bean
    public ElasticClient elasticClient(){
        return new ElasticClient(restHighLevelClient(), properties.getIndexName());
    }
}
